<?php

namespace App\Controllers\Admin;

use Page,Rate,View,Buyrecord,Area,Pub;
use Input, Notification, Redirect, Sentry, Str,Service;

use App\Services\Validators\PageValidator;

class BuyrecordsController extends \BaseController {

	/**
	 * Display a listing of the resource.
	 *
	 * @return Response
	 */
	public function index()
	{
		//
        $user = Sentry::getUser();


        $METHOD = 'buyrecords';
        $ACTION = 'index';

        // Check if the user has the 'admin' permission. Also,
        // multiple permissions may be used by passing an array
        if ($user->hasAccess('admin')){

            $buyrecords = Buyrecord::where('type','>',0)->orderBy('created_at', 'DESC')->paginate(20);
            return View::make('admin.buyrecords.admin_index',compact('METHOD','ACTION','buyrecords'));
        }else{
            $city = Area::find($user->city);
            $buyrecords = Buyrecord::where('city',$user->city)->orderBy('created_at', 'DESC')->paginate(20);
    //        $services = Service::where('section_id',$user->area)->orderBy('created_at', 'DESC')->paginate(20);
    //        $works = Work::where('section_id',$user->area)->orderBy('created_at', 'DESC')->get();
            return View::make('admin.buyrecords.index',compact('METHOD','ACTION','buyrecords','city'));
        }


	}


	/**
	 * Show the form for creating a new resource.
	 *
	 * @return Response
	 */
	public function create()
	{


	}


	/**
	 * Store a newly created resource in storage.
	 *
	 * @return Response
	 */
	public function store()
	{
		//

	}


	/**
	 * Display the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function show($id)
	{

	}


	/**
	 * Show the form for editing the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
		//
        $buyrecord = Buyrecord::find($id);

        $user = Sentry::getUser();


        $METHOD = 'buyrecords';
        $ACTION = 'index';
        // Check if the user has the 'admin' permission. Also,
        // multiple permissions may be used by passing an array
        if ($user->hasAccess('admin')){
            return View::make('admin.buyrecords.edit',compact('METHOD','ACTION','buyrecord'));
        }

	}


	/**
	 * Update the specified resource in storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id)
	{
		//
        $buyrecord = Buyrecord::find($id);
        $re = $this->hongbao($buyrecord->customer->openid,$buyrecord->out_trade_no,$buyrecord->Commodity->member_price,$buyrecord->Commodity->name);

        $postObj = simplexml_load_string($re, 'SimpleXMLElement', LIBXML_NOCDATA);

        if($postObj->return_code == 'SUCCESS'){
            $buyrecord = Buyrecord::where('out_trade_no',$postObj->partner_trade_no)->first();
            $buyrecord->type = 2;
            $buyrecord->pay_time = time();
            $buyrecord->total_fee = $buyrecord->Commodity->member_price;
            $buyrecord->save();
            return Redirect::route('admin.buyrecords.index');
        }else{
            echo $postObj->return_msg;
        }


    }


	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
		//
        $rate = Rate::findOrFail($id);
        $rate->delete();
//        Flash::success(lang('Operation succeeded.'));

        return Redirect::route('rates.index');

	}

    /**
     * @return mixed
     * 微信收款明细
     */
    public function collection(){

        if(Input::get('month') == ''){
            $thismonth = date('Y-m');
            $Begin = strtotime(date('Y-m-01'));
            $BeginDate=date('Y-m-01', $Begin);
            $End = strtotime("$BeginDate +1 month -1 day");

            $step = 0;
            $pagemonth ='';
        }else{
            if(Input::get('step') == 1){
                $DD = $this->getlastMonthDays(Input::get('month'));
            }elseif(Input::get('step') == 2){
                $DD = $this->getNextMonthDays(Input::get('month'));
            }
            $pagemonth = Input::get('month');
            $step = Input::get('step');
            $Begin = $DD[0];
            $End = $DD[1];
            $thismonth = date('Y-m', $Begin);



        }
        $user = Sentry::getUser();


        $METHOD = 'buyrecords';
        $ACTION = 'collection';

        // Check if the user has the 'admin' permission. Also,
        // multiple permissions may be used by passing an array
        if ($user->hasAccess('admin')){

            $services = Service::where('type',10)->where('all',1)->where('paytype',2)
                ->where('pay_time','>',$Begin)
                ->where('pay_time','<',$End)
                ->orderBy('created_at', 'DESC')->paginate(20);

        }elseif($user->hasAccess('city')){

            $services = Service::whereHas('customer', function($q) use($user)
            {
                $q->where('city', $user->city);

            })->where('type',10)->where('all',1)->where('paytype',2)
                ->where('pay_time','>',$Begin)
                ->where('pay_time','<',$End)
                ->orderBy('created_at', 'DESC')->paginate(20);
        }elseif($user->hasAccess('section')){

            $services = Service::whereHas('mount', function($q) use($user)
            {
                $q->where('section_id', $user->area);

            })->where('type',10)->where('all',1)->where('paytype',2)
                ->where('pay_time','>',$Begin)
                ->where('pay_time','<',$End)
                ->orderBy('created_at', 'DESC')->paginate(20);
        }
        return View::make('admin.buyrecords.collection',compact('METHOD','ACTION','services','thismonth','step','pagemonth'));
    }

    /**
     * @return mixed
     * 微信付款明细
     */
    public function payment(){
        if(Input::get('month') == ''){
            $thismonth = date('Y-m');
            $Begin = strtotime(date('Y-m-01'));
            $BeginDate=date('Y-m-01', $Begin);
            $End = strtotime("$BeginDate +1 month -1 day");

            $step = 0;
            $pagemonth = '';
        }else{
            if(Input::get('step') == 1){
                $DD = $this->getlastMonthDays(Input::get('month'));
            }elseif(Input::get('step') == 2){
                $DD = $this->getNextMonthDays(Input::get('month'));
            }
            $pagemonth = Input::get('month');
            $step = Input::get('step');
            $Begin = $DD[0];
            $End = $DD[1];
            $thismonth = date('Y-m', $Begin);



        }


        //
        $user = Sentry::getUser();


        $METHOD = 'buyrecords';
        $ACTION = 'payment';

        // Check if the user has the 'admin' permission. Also,
        // multiple permissions may be used by passing an array
        if ($user->hasAccess('admin')){

            $buyrecords = Buyrecord::whereHas('commodity', function($q)
            {
                $q->where('type', 4);

            })->where('type',2)
                ->where('pay_time','>',$Begin)
                ->where('pay_time','<',$End)
                ->orderBy('created_at', 'DESC')->paginate(20);

        }elseif($user->hasAccess('city')){
            $buyrecords = Buyrecord::whereHas('commodity', function($q)
            {
                $q->where('type', 4);

            })->whereHas('customer', function($q) use($user)
            {
                $q->where('city', $user->city);

            })->where('type',2)
                ->where('pay_time','>',$Begin)
                ->where('pay_time','<',$End)
                ->orderBy('created_at', 'DESC')->paginate(20);
        }elseif($user->hasAccess('section')){
            $buyrecords = Buyrecord::whereHas('commodity', function($q)
            {
                $q->where('type', 4);

            })->whereHas('customer', function($q) use($user)
            {
                $q->where('area', $user->area);

            })->where('type',2)
                ->where('pay_time','>',$Begin)
                ->where('pay_time','<',$End)
                ->orderBy('created_at', 'DESC')->paginate(20);
        }
        return View::make('admin.buyrecords.payment',compact('METHOD','ACTION','buyrecords','thismonth','step','pagemonth'));
    }

    public function getlastMonthDays($date){
        $timestamp=strtotime($date);
        $firstday=strtotime(date('Y',$timestamp).'-'.(date('m',$timestamp)-1).'-01');
        $lastday=strtotime("$firstday +1 month -1 day");
        return array($firstday,$lastday);
    }

    public function getNextMonthDays($date){
        $timestamp=strtotime($date);
        $arr=getdate($timestamp);
        if($arr['mon'] == 12){
            $year=$arr['year'] +1;
            $month=$arr['mon'] -11;
            $firstday=$year.'-0'.$month.'-01';
            $firstday = strtotime($firstday);
            $lastday=strtotime("$firstday +1 month -1 day");
        }else{
            $firstday=strtotime(date('Y',$timestamp).'-'.(date('m',$timestamp)+1).'-01');
            $lastday=strtotime("$firstday +1 month -1 day");
        }
        return array($firstday,$lastday);
    }

    public function explode(){

        $user = Sentry::getUser();

        if(Input::get('step') == 'payment'){

            $thismonth = Input::get('month');
            $Begin = strtotime(date(Input::get('month').'-01'));
            $BeginDate=date('Y-m-01', $Begin);
            $End = strtotime("$BeginDate +1 month -1 day");


            if ($user->hasAccess('admin')){

                $buyrecords = Buyrecord::whereHas('commodity', function($q)
                {
                    $q->where('type', 4);

                })->where('type',2)
                    ->where('pay_time','>',$Begin)
                    ->where('pay_time','<',$End)
                    ->orderBy('created_at', 'DESC')->get();

            }elseif($user->hasAccess('city')){
                $buyrecords = Buyrecord::whereHas('commodity', function($q)
                {
                    $q->where('type', 4);

                })->whereHas('customer', function($q) use($user)
                {
                    $q->where('city', $user->city);

                })->where('type',2)
                    ->where('pay_time','>',$Begin)
                    ->where('pay_time','<',$End)
                    ->orderBy('created_at', 'DESC')->get();
            }elseif($user->hasAccess('section')){
                $buyrecords = Buyrecord::whereHas('commodity', function($q)
                {
                    $q->where('type', 4);

                })->whereHas('customer', function($q) use($user)
                {
                    $q->where('area', $user->area);

                })->where('type',2)
                    ->where('pay_time','>',$Begin)
                    ->where('pay_time','<',$End)
                    ->orderBy('created_at', 'DESC')->get();
            }



            $this->_payment_excel($buyrecords,$thismonth);


        }elseif(Input::get('step') == 'collection'){

            $thismonth = Input::get('month');
            $Begin = strtotime(date(Input::get('month').'-01'));
            $BeginDate=date('Y-m-01', $Begin);
            $End = strtotime("$BeginDate +1 month -1 day");

            if ($user->hasAccess('admin')){

                $services = Service::where('type',10)->where('all',1)->where('paytype',2)
                    ->where('pay_time','>',$Begin)
                    ->where('pay_time','<',$End)
                    ->orderBy('created_at', 'DESC')->get();

            }elseif($user->hasAccess('city')){

                $services = Service::whereHas('customer', function($q) use($user)
                {
                    $q->where('city', $user->city);

                })->where('type',10)->where('all',1)->where('paytype',2)
                    ->where('pay_time','>',$Begin)
                    ->where('pay_time','<',$End)
                    ->orderBy('created_at', 'DESC')->get();
            }elseif($user->hasAccess('section')){

                $services = Service::whereHas('mount', function($q) use($user)
                {
                    $q->where('section_id', $user->area);

                })->where('type',10)->where('all',1)->where('paytype',2)
                    ->where('pay_time','>',$Begin)
                    ->where('pay_time','<',$End)
                    ->orderBy('created_at', 'DESC')->get();
            }

            $this->_collection_excel($services,$thismonth);
        }
    }





    protected function _payment_excel($lists,$title){

        require app_path().'/lib/Excel/PHPExcel.php';
        $objPHPExcel=new \PHPExcel();
        $objPHPExcel->getProperties()->setCreator('http://www.jb51.net')
            ->setLastModifiedBy('http://www.jb51.net')
            ->setTitle('Office 2007 XLSX Document')
            ->setSubject('Office 2007 XLSX Document')
            ->setDescription('Document for Office 2007 XLSX, generated using PHP classes.')
            ->setKeywords('office 2007 openxml php')
            ->setCategory('Result file');
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1','城市')
            ->setCellValue('B1','直营商')
            ->setCellValue('C1','昵称')
            ->setCellValue('D1','客户')
            ->setCellValue('E1','联系方式')
            ->setCellValue('F1','收获地址')
            ->setCellValue('G1','订单编号')
            ->setCellValue('H1','付款时间')
            ->setCellValue('I1','付款金额');

//        var_dump($list);
        $i = 2;
        foreach($lists as $list){
            $father = $list->fathercity->username;
            if($father == ''){
                $father = ' ';
            }
            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValueExplicit('A'.$i,$list->customer->cityname->name,\PHPExcel_Cell_DataType::TYPE_STRING)
                ->setCellValueExplicit('B'.$i,$list->customer->areaname->name,\PHPExcel_Cell_DataType::TYPE_STRING)
                ->setCellValue('C'.$i,$list->customer->name)
                ->setCellValue('D'.$i,$list->name)
                ->setCellValueExplicit('E'.$i,$list->mobile,\PHPExcel_Cell_DataType::TYPE_STRING)
                ->setCellValue('F'.$i,$list->address)
                ->setCellValueExplicit('G'.$i,$list->out_trade_no,\PHPExcel_Cell_DataType::TYPE_STRING)
                ->setCellValue('H'.$i,date('Y-m-d',$list->pay_time))
                ->setCellValue('I'.$i,$list->total_fee);
            $i++;
        }

        $objPHPExcel->getActiveSheet()->setTitle('Sheet1');
        $objPHPExcel->setActiveSheetIndex(0);
        $filename=urlencode('微信付款').'_'.$title;
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$filename.'.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');


        $objWriter->save('php://output');

    }



    protected function _collection_excel($lists,$title){

        require app_path().'/lib/Excel/PHPExcel.php';
        $objPHPExcel=new \PHPExcel();
        $objPHPExcel->getProperties()->setCreator('http://www.jb51.net')
            ->setLastModifiedBy('http://www.jb51.net')
            ->setTitle('Office 2007 XLSX Document')
            ->setSubject('Office 2007 XLSX Document')
            ->setDescription('Document for Office 2007 XLSX, generated using PHP classes.')
            ->setKeywords('office 2007 openxml php')
            ->setCategory('Result file');
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1','城市')
            ->setCellValue('B1','直营商')
            ->setCellValue('C1','昵称')
            ->setCellValue('D1','客户')
            ->setCellValue('E1','联系方式')
            ->setCellValue('F1','订单编号')
            ->setCellValue('G1','付款时间')
            ->setCellValue('H1','收入金额');

//        var_dump($list);
        $i = 2;
        foreach($lists as $list){
            $father = $list->fathercity->username;
            if($father == ''){
                $father = ' ';
            }
            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValueExplicit('A'.$i,$list->mount->cityname->name,\PHPExcel_Cell_DataType::TYPE_STRING)
                ->setCellValueExplicit('B'.$i,$list->mount->section->name,\PHPExcel_Cell_DataType::TYPE_STRING)
                ->setCellValue('C'.$i,$list->customer->name)
                ->setCellValue('D'.$i,$list->mount->mount_name)
                ->setCellValueExplicit('E'.$i,$list->mount->mount_mobile,\PHPExcel_Cell_DataType::TYPE_STRING)
                ->setCellValueExplicit('F'.$i,$list->service_num,\PHPExcel_Cell_DataType::TYPE_STRING)
                ->setCellValue('G'.$i,date('Y-m-d',$list->pay_time))
                ->setCellValue('H'.$i,$list->total_fee/100);
            $i++;
        }

        $objPHPExcel->getActiveSheet()->setTitle('Sheet1');
        $objPHPExcel->setActiveSheetIndex(0);
        $filename=urlencode('微信收款').'_'.$title;
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$filename.'.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');


        $objWriter->save('php://output');

    }


    public function check_order(){

        $id = Input::get('id');
        $buycheck = Buyrecord::find($id);
        if(Input::get('ship') == 1){
            $buycheck->type = 3;
        }else{
            $buycheck->type = 1;
        }
        $buycheck->save();
        echo 1;
    }


    public function hongbao22(){

        $pub = Pub::find(1);
        $appid = $pub->AppID;

        $billno = '1226760102'.date('Ymd').rand(1000000000,999999999);
//        $xml = '<xml>
//  <openid><![CDATA['.$openid.']]></openid>
//  <body><![CDATA['.$body.']]></body>
//  <out_trade_no><![CDATA['.$time.']]></out_trade_no>
//  <total_fee>'.$total.'</total_fee>
//  <notify_url><![CDATA[http://crm.leaderphos.com/pay/buy_notify/]]></notify_url>
//  <trade_type><![CDATA[JSAPI]]></trade_type>
//  <appid><![CDATA['.$appid.']]></appid>
//  <mch_id>1226760102</mch_id>
//  <spbill_create_ip><![CDATA['.$_SERVER['REMOTE_ADDR'].']]></spbill_create_ip>
//  <nonce_str><![CDATA[60uf9sh6nmppr9azveb2bn7arhy79izk]]></nonce_str>
//</xml>';
        $xml = '
<xml>
            <mch_billno><![CDATA['.$billno.']]></mch_billno>
            <mch_id><![CDATA[1226760102]]></mch_id>
            <wxappid><![CDATA['.$appid.']]></wxappid>
            <nick_name><![CDATA[雷谛科技]]></nick_name>
            <send_name><![CDATA[雷谛科技]]></send_name>
            <re_openid><![CDATA[o-5gRt7rCLKuA5nwrCtqLqOOAe7c]]></re_openid>
            <total_amount>100</total_amount>
            <min_value>100</min_value>
            <max_value>100</max_value>
            <total_num>1</total_num>
            <wishing><![CDATA[hello]]></wishing>
            <client_ip><![CDATA[114.80.156.65]]></client_ip>
            <act_name><![CDATA[阿斯顿发送到]]></act_name>
            <remark><![CDATA[你好]]></remark>
            <nonce_str><![CDATA[5K8264ILTKCH16CQ2502SI8ZNMTM67VS]]></nonce_str>
        </xml>';
//        $xml = '1';

        $arr = $this->xmlToArray($xml); //转成数组

        var_dump($arr);
        $str = $this->formatBizQueryParaMap($arr,false); //字典序排序 1
        $stringSignTemp = $str.'&key='.$pub->apiKey;  //把key拼接上 2
        $md5 = md5($stringSignTemp); //md5 3
        $sign = strtoupper($md5); //再转大写 获取sign 4


        $x = '
<xml>
            <mch_billno><![CDATA['.$billno.']]></mch_billno>
            <mch_id><![CDATA[1226760102]]></mch_id>
            <wxappid><![CDATA['.$appid.']]></wxappid>
            <nick_name><![CDATA[雷谛科技]]></nick_name>
            <send_name><![CDATA[雷谛科技]]></send_name>
            <re_openid><![CDATA[o-5gRt7rCLKuA5nwrCtqLqOOAe7c]]></re_openid>
            <total_amount>100</total_amount>
            <min_value>100</min_value>
            <max_value>100</max_value>
            <total_num>1</total_num>
            <wishing><![CDATA[hello]]></wishing>
            <client_ip><![CDATA[114.80.156.65]]></client_ip>
            <act_name><![CDATA[阿斯顿发送到]]></act_name>
            <remark><![CDATA[你好]]></remark>
            <nonce_str><![CDATA[5K8264ILTKCH16CQ2502SI8ZNMTM67VS]]></nonce_str>
              <sign><![CDATA['.$sign.']]></sign>
        </xml>';
        $data = $this->curl_post_ssl('https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack',$x);
        echo $data;
    }



    public function hongbao($openid,$billno,$price,$desc){
        $pay = $price*100;
        $pub = Pub::find(1);
        $appid = $pub->AppID;
//        $xml = '<xml>
//  <openid><![CDATA['.$openid.']]></openid>
//  <body><![CDATA['.$body.']]></body>
//  <out_trade_no><![CDATA['.$time.']]></out_trade_no>
//  <total_fee>'.$total.'</total_fee>
//  <notify_url><![CDATA[http://crm.leaderphos.com/pay/buy_notify/]]></notify_url>
//  <trade_type><![CDATA[JSAPI]]></trade_type>
//  <appid><![CDATA['.$appid.']]></appid>
//  <mch_id>1226760102</mch_id>
//  <spbill_create_ip><![CDATA['.$_SERVER['REMOTE_ADDR'].']]></spbill_create_ip>
//  <nonce_str><![CDATA[60uf9sh6nmppr9azveb2bn7arhy79izk]]></nonce_str>
//</xml>';
        $xml = '
<xml>
            <partner_trade_no><![CDATA['.$billno.']]></partner_trade_no>
            <mchid><![CDATA[1226760102]]></mchid>
            <mch_appid><![CDATA['.$appid.']]></mch_appid>
            <openid><![CDATA['.$openid.']]></openid>
            <amount>'.$pay.'</amount>
            <check_name><![CDATA[NO_CHECK]]></check_name>
            <spbill_create_ip><![CDATA[114.80.156.65]]></spbill_create_ip>
            <desc><![CDATA['.$desc.']]></desc>
            <nonce_str><![CDATA[5K826416CQ2502SI8ZNMTM67VSILTKCH]]></nonce_str>
        </xml>';
//        $xml = '1';

        $arr = $this->xmlToArray($xml); //转成数组

//        var_dump($arr);
        $str = $this->formatBizQueryParaMap($arr,false); //字典序排序 1
        $stringSignTemp = $str.'&key='.$pub->apiKey;  //把key拼接上 2
        $md5 = md5($stringSignTemp); //md5 3
        $sign = strtoupper($md5); //再转大写 获取sign 4


        $x = '
<xml>
            <partner_trade_no><![CDATA['.$billno.']]></partner_trade_no>
            <mchid><![CDATA[1226760102]]></mchid>
            <mch_appid><![CDATA['.$appid.']]></mch_appid>
            <openid><![CDATA['.$openid.']]></openid>
            <amount>'.$pay.'</amount>
            <check_name><![CDATA[NO_CHECK]]></check_name>
            <spbill_create_ip><![CDATA[114.80.156.65]]></spbill_create_ip>
            <desc><![CDATA['.$desc.']]></desc>
            <nonce_str><![CDATA[5K826416CQ2502SI8ZNMTM67VSILTKCH]]></nonce_str>
              <sign><![CDATA['.$sign.']]></sign>
        </xml>';
        $data = $this->curl_post_ssl('https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers',$x);
        return $data;
    }




    function curl_post_ssl($url, $vars, $second=30,$aHeader=array())
    {
        $ch = curl_init();
        //超时时间
        curl_setopt($ch,CURLOPT_TIMEOUT,$second);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
        //这里设置代理，如果有的话
        //curl_setopt($ch,CURLOPT_PROXY, '10.206.30.98');
        //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);

        //以下两种方式需选择一种

        //第一种方法，cert 与 key 分别属于两个.pem文件
        //默认格式为PEM，可以注释
        curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
        curl_setopt($ch,CURLOPT_SSLCERT,'/apiclient_cert.pem');
        //默认格式为PEM，可以注释
        curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
        curl_setopt($ch,CURLOPT_SSLKEY,'/apiclient_key.pem');

        //第二种方式，两个文件合成一个.pem文件
//        curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/all.pem');

        if( count($aHeader) >= 1 ){
            curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
        }

        curl_setopt($ch,CURLOPT_POST, 1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$vars);
        $data = curl_exec($ch);
        if($data){
            curl_close($ch);
            return $data;
        }
        else {
            $error = curl_errno($ch);
            echo "call faild, errorCode:$error\n";
            curl_close($ch);
            return false;
        }
    }

    /**
     *  作用：以post方式提交xml到对应的接口url
     */
    function postXmlCurl($url,$xml,$second=30){
        //初始化curl
        $ch = curl_init();
        //设置超时
        //curl_setopt($ch, CURLOP_TIMEOUT, $second);
        //这里设置代理，如果有的话
        //curl_setopt($ch,CURLOPT_PROXY, '8.8.8.8');
        //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
        curl_setopt($ch,CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
        //设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        //post提交方式
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        //运行curl
        $data = curl_exec($ch);
        curl_close($ch);
        //返回结果
        if($data){
            //curl_close($ch);
            return $data;
        }else{
            $error = curl_errno($ch);
            echo "curl出错，错误码:$error"."<br>";
            echo "<a href='http://curl.haxx.se/libcurl/c/libcurl-errors.html'>错误原因查询</a></br>";
            curl_close($ch);
            return false;
        }
    }

    /**
     *  作用：将xml转为array
     */
    function xmlToArray($xml){
        //将XML转为array
        $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $array_data;
    }


    /**
     *  作用：格式化参数，签名过程需要使用
     */
    function formatBizQueryParaMap($paraMap, $urlencode){
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v){
            if($urlencode){
                $v = urlencode($v);
            }
            //$buff .= strtolower($k) . "=" . $v . "&";
            $buff .= $k . "=" . $v . "&";
        }
        $reqPar;
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff)-1);
        }
        return $reqPar;
    }


}
